//
//  UserDetailedInfoViewController.m
//  HuLaQuan
//
//  Created by hok on 1/15/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "UserDetailedInfoViewController.h"



#import "SetUserInfoEngine.h"

//Cells
#import "UserTextInfoCell.h"
#import "UserTypeInfoCell.h"
#import "UserPhotoCell.h"

#import "YuUserCellLabel.h"
#import "YuLoginInputInfoField.h"

//Image Taker View
#import "AQPhotoPickerView.h"
#import "PhotoController.h"

#import "UIImage+YuExt.h"

@interface UserDetailedInfoViewController  ()<UIActionSheetDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate,AQPhotoPickerViewDelegate>

@property (strong, nonatomic) NSArray *userInfoKeys; //of keys;

@property (strong, nonatomic) SetUserInfoEngine *setUserInfoEngine;

@property (strong, nonatomic) NSIndexPath *selectIndexPath;

@property(assign,nonatomic)NSInteger index;

@property(strong,nonatomic)UITapGestureRecognizer *tap;


@property(strong,nonatomic) UIImage *takenImage;
@property(strong,nonatomic) NSDictionary *takenImageInfo;

//username
@property(strong,nonatomic)NSString *userName;
@property(strong,nonatomic)NSString *sexChoose;

@end

static NSString * const UserTextInfoCellIdentifier = @"UserTextInfoCell";
static NSString * const UserTypeInfoCellIdentifier = @"UserTypeInfoCell";
static NSString * const UserPhotoCellIdentifier = @"UserPhotoCell";

@implementation UserDetailedInfoViewController
- (SetUserInfoEngine *)setUserInfoEngine
{
    if (!_setUserInfoEngine) {
        _setUserInfoEngine = [[SetUserInfoEngine alloc] init];
    }
    return _setUserInfoEngine;
}
- (NSArray *)userInfoKeys
{
    if (!_userInfoKeys) {
        _userInfoKeys = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"UserInfoKeys" ofType:@"plist"]];
    }
    return _userInfoKeys;
}

- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    //判断是否对性别做出了选择
    self.index = 3;
    
    [self.tableView registerNib:[UserTextInfoCell nib] forCellReuseIdentifier:UserTextInfoCellIdentifier];
    [self.tableView registerNib:[UserTypeInfoCell nib] forCellReuseIdentifier:UserTypeInfoCellIdentifier];
    [self.tableView registerNib:[UserPhotoCell nib] forCellReuseIdentifier:UserPhotoCellIdentifier];
    
    self.title = @"个人信息";
}
// 加手势处理键盘
- (void)setupTapGesture
{
    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handelGenericTapView:)];
    _tap.delegate = self;
    [self.view addGestureRecognizer:_tap];
}
- (void)handelGenericTapView:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // handling code
        //[self.view endEditing:YES];
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
}
#pragma mark - Call Back
#pragma mark - Callback
- (void)setUserInfoFinish:(NSNotification * )notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    
    if ([messageDic[@"isSuccess"] boolValue]) {
        [self.view makeToast:@"修改信息成功"];
        if([messageDic[@"result"] isEqualToString:@"avatar"]){
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            [self.getUserInfoEngine getUserInfo];
        }
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        self.userInfo = messageDic[@"result"];
        [self.tableView reloadData];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUserInfoFinish:) name:@"SetUserInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SetUserInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
    [super viewWillDisappear:YES];
}



#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.placeholder = nil;
    // 加手势处理键盘
    [self setupTapGesture];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length == 0 ) {
        YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
        
        textF.placeholder = self.userInfoKeys[textField.tag][@"title"];
    }else{
        if (![self.userName isEqualToString:self.userInfo[@"nickname"]]) {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            [self.setUserInfoEngine setUserInfo:self.userName withTag:@"nickname"];
        }
    }
    [self.view removeGestureRecognizer:_tap];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return kUserPhotoCellHeight;
            break;
        case 1:
            return kNormalCellHeight;
            break;
            
        default:
            return 0;
            break;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        default:
            return 0;
            break;
    }
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 40;
            break;
        case 1:
            return 0.00001;
            break;
        default:
            return 0;
            break;
    }
    
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    switch (section) {
        case 0:
        {
            CGRect frameRect = CGRectMake(10, 0, 200, 40);
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
            YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
            textSection.text = @"基本信息";
            [view addSubview:textSection];
            return view;
        }
            break;
        case 1:
        {
            return nil;
        }
            break;
        default:
            return 0;
            break;
    }
    
    
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            UserPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:UserPhotoCellIdentifier
                                                                  forIndexPath:indexPath];
            if (self.userInfo[@"avatar"] ) {
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                
                NSString *filePath = [NSString stringWithFormat:@"%@/%@",[NSString photoDir],kTempLocalAvatarName];
                if (![fileManager fileExistsAtPath:filePath]) {
                    cell.avatar.image = [UIImage imageNamed:@"default_user"];
                }else{
                    
                    cell.avatar.image = [UIImage imageWithContentsOfFile:filePath];
                }
            }else{
                cell.avatar.image = [UIImage imageNamed:@"default_user"];
            }
            return cell;
        }
            break;
        case 1:
        {
            if (indexPath.row == 0) {
                UserTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:UserTypeInfoCellIdentifier
                                                                         forIndexPath:indexPath];
                
                if (self.userInfo && self.userInfo[@"nickname"]) {
                    
                    self.userName = self.userInfo[@"nickname"];
                    cell.textField.text = self.userName ;
                }
                cell.textField.placeholder = self.userInfoKeys[indexPath.row][@"title"];
                
                [cell.textField addTarget:self action:@selector(detaileAddressFieldWithText:) forControlEvents:UIControlEventEditingChanged];
                
                cell.textField.delegate = self;
                cell.textField.tag = indexPath.row;
                return cell;
                
            }else{
                UserTextInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:UserTextInfoCellIdentifier
                                                                         forIndexPath:indexPath];
                
                
                if (self.index == 3) {
                    
                    cell.titleLabel.text = self.userInfoKeys[indexPath.row][@"title"];
                    self.sexChoose = cell.textLabel.text;
                }
                else if(_index == 0 || _index == 1)
                {
                    cell.titleLabel.text = [self.userInfoKeys[indexPath.row][@"options"]objectAtIndex:_index];
                    self.sexChoose = cell.textLabel.text;
                }
                
                return cell;
            }

        }
        default:
            return nil;
            break;
    }
    
    
}

//getInformation
- (void)detaileAddressFieldWithText:(UITextField *)textField
{
    self.userName = textField.text;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    switch (indexPath.section) {
        case 0:
        {
            PhotoController *photo = [[PhotoController alloc]init];
            photo.view.frame = CGRectMake(0, self.view.frame.size.height-150,self.view.frame.size.width ,150 );
            [self addChildViewController:photo];
            [self.view addSubview:photo.view];
            photo.delegateViewController = self;
        }
            break;
        case 1:
        {if (1 == indexPath.row) {
            //        NSMutableString *string =[NSMutableString string];
            
            
            UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                          initWithTitle:@"性别选择"
                                          delegate:self
                                          cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                          otherButtonTitles: nil];
            
            for (NSString *object in self.userInfoKeys[indexPath.row][@"options"]) {
                
                [actionSheet addButtonWithTitle:object ];
                
            }
            //        actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
            [actionSheet showInView:self.view];
            
            
        }

            
        }
            break;
        default:
            break;
    }
}

#pragma mark - AQPhotoPickerViewDelegate methods
-(void)photoFromImagePickerView:(UIImage*) photo {
    
    self.takenImage = photo;
    
   // [self.imageArray setObject:photo atIndexedSubscript:0];
    if ([photo saveImageWithName:kTempLocalAvatarName]) {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.setUserInfoEngine setUserInfo:self.takenImage withTag:@"avatar"];
    }
    
    
    
}

//点击按钮时触发的方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
   // NSLog(@"buttonIndex:%ld",buttonIndex);
    _index = buttonIndex-1;
    
    [self.tableView reloadData];
}
@end
